Param(
  [int]$Port = 3000,
  [string]$UrlPath = "/analysis"
)

Write-Host "[frontend] Starting Next.js dev server on port $Port..." -ForegroundColor Cyan

# Resolve directories
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$RootDir = Resolve-Path (Join-Path $ScriptDir "..")
$FrontendDir = Join-Path $RootDir "lm-frontend"

if (!(Test-Path $FrontendDir)) {
  Write-Error "Frontend directory not found: $FrontendDir"
  exit 1
}

# Check node/npm
try { node -v | Out-Null } catch { Write-Error "Node.js is not installed or not in PATH."; exit 1 }
try { npm -v  | Out-Null } catch { Write-Error "npm is not installed or not in PATH."; exit 1 }

# Ensure .env.local exists for API base URL
$envFile = Join-Path $FrontendDir ".env.local"
if (!(Test-Path $envFile)) {
$defaultApi = "auto"
  "NEXT_PUBLIC_API_BASE_URL=$defaultApi" | Out-File -Encoding UTF8 $envFile
  Write-Host "[frontend] Created .env.local with NEXT_PUBLIC_API_BASE_URL=$defaultApi (proxy via Next rewrites)" -ForegroundColor DarkGray
}

# Install deps if needed
if (!(Test-Path (Join-Path $FrontendDir "node_modules"))) {
  Write-Host "[frontend] Installing dependencies (npm install)..." -ForegroundColor DarkGray
  Push-Location $FrontendDir
  npm install
  if ($LASTEXITCODE -ne 0) { Write-Error "npm install failed"; Pop-Location; exit 1 }
  Pop-Location
}

# Start dev server in a new window
Write-Host "[frontend] Launching dev server..." -ForegroundColor DarkGray
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = "cmd.exe"
$psi.Arguments = "/c npm run dev"
$psi.WorkingDirectory = $FrontendDir
$psi.UseShellExecute = $true
$psi.WindowStyle = 'Normal'
[System.Diagnostics.Process]::Start($psi) | Out-Null

# Wait for server
$url = "http://localhost:$Port"
Write-Host "[frontend] Waiting for $url to be ready..." -ForegroundColor DarkGray
$maxAttempts = 120
for ($i = 1; $i -le $maxAttempts; $i++) {
  try {
    $res = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 2
    if ($res.StatusCode -ge 200 -and $res.StatusCode -lt 500) { break }
  } catch {
    Start-Sleep -Milliseconds 1000
  }
}

Start-Process "$url$UrlPath"
Write-Host "[frontend] Opened $url$UrlPath in your default browser." -ForegroundColor Green
